Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.IO
Imports MyFramework

Public Class BOSalesReport
    Inherits System.Web.UI.Page

    Protected WithEvents header As BOReportHeader

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ddlSupplier As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlOwner As System.Web.UI.WebControls.DropDownList
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents ddlType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlTarget As System.Web.UI.WebControls.DropDownList
    Protected WithEvents dlReport As System.Web.UI.WebControls.DataList
    Protected WithEvents btnExportPDF As System.Web.UI.WebControls.LinkButton

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Protected Function GetPackTypeText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackTypeMeaning(Convert.toString(data))
        End If
    End Function

    Protected Function GetPackType2Text(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackType2Meaning(Convert.toString(data))
        End If
    End Function

    Protected Function GetPackTypeTextNotNull(ByVal data As Object, ByVal pack As Object) As String

        If data Is DBNull.Value OrElse Convert.toString(data).Trim.Length = 0 Then
            Return "&nbsp;"
        Else
            Dim dummy As Integer = 0
            Try
                dummy = Convert.ToInt32(data)
            Catch ex As Exception

            End Try
            If dummy = Nulls.NullInteger Then
                Return "&nbsp;"
            Else
                Return GetPackTypeText(pack)
            End If
        End If
    End Function

    Protected Function GetQtyAvailHTML(ByVal container As Object) As String
        Dim bo As BulkOrder = CType(container, BulkOrder)
        'Dim qtyAvail As Integer = bo.QuantityAvailable        
        'Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty

        'Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        Try
            If (bo.IDSQuantityAvail <> Nulls.NullInteger) Then
                Return bo.IDSQuantityAvail.ToString()
            Else
                Return "&nbsp;"
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try

    End Function

    Protected Function GetQtyAvailDesc(ByVal container As Object) As String
        Dim bo As BulkOrder = CType(container, BulkOrder)
        Dim qtyAvail As Integer = bo.QuantityAvailable
        Dim catPackDesc As String = bo.CatPackDesc
        Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty
        Dim unitDesc As String = bo.Pack

        Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        If (isShownInLGD = True) Then
            'Logger.Debug("packQty: " + packQty.ToString())
            'Logger.Debug("catPackDesc: " + catPackDesc)
            'Logger.Debug("GetPackType2Text: " + GetPackType2Text(catPackDesc))
            If packQty <> Nulls.NullInteger Then
                Return GetPackType2Text(catPackDesc)
            Else
                Return "&nbsp;"
            End If
        Else
            If qtyAvail <> Nulls.NullInteger Then
                Return GetPackTypeText(unitDesc)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetFOB(ByVal data As Object, ByVal unitDesc As String) As String
        If data Is DBNull.Value Or Convert.ToDecimal(data) = Nulls.NullDecimal Then
            Return "&nbsp;"
        Else
            Return String.Format("{0} (USD) per {1}", _
                (Convert.ToDecimal(data) * (1 - RequestContext.Discount / 100)).ToString(Config.DecimalFormat), _
                BulkOrder.GetBOPackTypeMeaning(unitDesc))
        End If
    End Function

    Protected Function GetPictureHTML(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Dim filePath As String = String.Format("{0}.jpg", Path.Combine(Config.ProductImagePath, Convert.toString(data)))

            If File.Exists(filePath) Then
                Return String.Format("<img src='../ViewPicture.aspx?procode={0}&size={1}' border=0 alt='{0}.jpg'>", data, Config.BOSalesReportImageSize)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function


    Protected Function GetClearanceStockHTML(ByVal container As Object) As String
        Dim _idsSort As String = Convert.ToString(DataBinder.Eval(container, "DataItem.IDSSort"))
        If (_idsSort.Trim().ToUpper() = "CLEARANCE STOCK") Then
            Return String.Format("<br><font color='red'>{0}</font>", "Clearance Stock - Priced to Clear !")
        Else
            Return ""
        End If
    End Function

    Private Function GetSource() As BulkOrderCollection
        Dim boType As Int32 = -1
        If Not Request.QueryString("type") Is Nothing Then
            boType = RequestContext.BOType
        End If

        Dim target As Int32 = -1
        If Not Request.QueryString("target") Is Nothing Then
            target = RequestContext.Target
        End If

        Return BulkOrderService.GetBulkOrdersSalesReport(RequestContext.ConPointID, RequestContext.SupplierCode, _
                RequestContext.Owner, RequestContext.BOType, RequestContext.Target, RequestContext.ReportType, _
                RequestContext.Quantity, RequestContext.CurrentUser.LOGIN_NAME)
    End Function

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            If RequestContext.DoReport Then
                Me.dlReport.DataSource = GetSource()
                Me.dlReport.DataBind()
            End If
        End If
    End Sub

    Private Sub header_ExportPDFClick() Handles header.ExportPDFClick
        Dim source As BulkOrderCollection = GetSource()
        Dim boXml As String = RenderService.GenerateBOXML(source, Config.ProductImagePath, RequestContext.Discount, RequestContext.ShowFOB).OuterXml
        Dim xslFile As String = Server.MapPath("../foxsl/fo.xsl")
        Dim foFile As String = Server.MapPath("../foTemp/" + String.Format("{0}{1}{2}{3}{4}{5}{6}.fo", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond))
        Dim pdfFile As String = String.Format("BOSalesReport_{0}{1}{2}{3}{4}{5}{6}.pdf", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond)
        Try
            If RenderService.GenerateFO(boXml, xslFile, foFile) Then
                Dim buffer() As Byte = RenderService.RenderFOtoPDF(foFile)
                File.Delete(foFile)

                Response.Clear()
                Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode(pdfFile)))
                Response.AddHeader("Content-Type", "application/pdf")
                Response.BinaryWrite(buffer)
                Response.Flush()
                Response.End()

            End If
        Catch ex As Exception
            Logger.Debug("Failed to render BO SalesReport PDF", ex)
        End Try

    End Sub

    Private Sub header_OKClick(ByVal conPointID As Integer, ByVal suppCode As String, ByVal owner As Integer, ByVal type As Integer, ByVal target As Integer, ByVal discount As Decimal, ByVal showFOB As Boolean, ByVal qty As Integer, ByVal notAvailInUSA As Boolean) Handles header.OKClick
        Response.Redirect(String.Format("BOSalesReport.aspx?sup={0}&owner={1}&type={2}&target={3}&rt={4}&discount={5}&showfob={6}&cpid={7}&naUSA={8}&qty={9}&dorpt=1", _
                   suppCode, owner, type, target, RequestContext.ReportType, discount, Convert.ToInt32(showFOB), conPointID, Convert.ToInt32(notAvailInUSA), qty))
    End Sub

    Private Sub dlReport_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlReport.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim ltrItemIndex As Literal = CType(e.Item.FindControl("ltrItemIndex"), Literal)
            ltrItemIndex.Text = (e.Item.ItemIndex + 1).ToString()
        End If
    End Sub
End Class
